var old_g_details;
var new_g_details;
var reset_pressed;

//1--- reset button is pressed.2--- load function is revoked.3--- load completed/start point.

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    var name = 	$('#g_update_name'),
	title = $('#g_update_title'),
	description = $('#g_update_desc'),
	member_limit = $('#g_update_limit'),
	photo = $('#g_update_photo'),

	
	options = {        //target:        '#output1',   // target element(s) to be updated with server response 
		beforeSubmit:  showRequest,  // pre-submit callback 
		success:       showResponse,  // post-submit callback 
		iframe: true,

		// other available options: 
		//url: '/group/'+ groupId + '/update/', 
		type:  'post',  
		dataType:  'json', 

		// $.ajax options can be used here too, for example: 
		timeout:   3000,
	},
	
	allFields = $([]).add(name).add(title).add(description).add(member_limit).add(photo),
	
	tips = $("#validateTips"),
	submitted = false,
	reset_pressed = false;
	
	old_g_details={
		name:$('#g_update_name').val(),
		title:$('#g_update_title').val(),
		description:$('#g_update_desc').val(),
		member_limit:$('#g_update_limit').val(),
		photo:$('#g_update_photo').val(),
		city:$('#city').val(),
		district:last_dist
	};
	
	$('#district').load('/location/district/', {'city':$('#city').val()}, function(){
		$('form#g_update_form select#district').each(function(){
			this.value=last_dist;
		});
	});
	
	$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 460,
			width: 400,
			resizable: false,
			modal: true,
			show: 'drop',
			hide: 'drop',
			buttons: {
				'重置修改':function(){
					reset();
				},
				'保存修改': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(name,"小组名称",2,100);
					bValid = bValid && checkLength(title,"小组标题",2,100);
					bValid = bValid && checkLength(member_limit,"活动成员上限",1,5);
					bValid = bValid && checkLength(description,"小组宣言",0,5000);

					//currently no reg test will be execute
					
					//bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					//bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
					//bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
					
					if (bValid) {
					//if validated, save the form to the server.
						$('#g_update_form').submit();
						submitted = true;
						$(this).dialog('close');
					}
				}
			},
			close: function() {
				//remove the checkbox for the reminder.
				//and the message in the tips
				//and the errors leave in fields
				if(submitted == false) reset();
				$('#notify_all').removeAttr("checked");
				
			}
		});
		
		    // bind form using 'ajaxForm'
			//$('#g_update_form').ajaxForm(options);
		$('#g_update_form').submit(function() { 
			// inside event callbacks 'this' is the DOM element so we first 
			// wrap it in a jQuery object and then invoke ajaxSubmit 
			$(this).ajaxSubmit(options); 
	 
			// !!! Important !!! 
			// always return false to prevent standard browser submit and page navigation 
			return false; 
		}); 
		
		$('#edit_group').click(function() {
			$('#dialog').dialog('open');
		})
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			$(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
				$(this).removeClass("ui-state-active");
		});
}); 

function updateTips(t) {
	tips.text(t).effect("highlight",{},1500);
}
function reset(){
	var reload_d = false;
	reset_pressed = true;
	updateTips("在下方输入要修改的信息");
	allFields.removeClass('ui-state-error');
	
	$('#g_update_name').val(old_g_details.name);
	$('#g_update_title').val(old_g_details.title);
	$('#g_update_desc').val(old_g_details.description);
	$('#g_update_limit').val(old_g_details.member_limit);
	$('#g_update_photo').val(old_g_details.photo);
	$('form#g_update_form select#city').each(function(){
		if(this.value!=old_g_details.city){
			this.value=old_g_details.city;
			reload_d = true;
		}
	});
	if(reload_d){
		$('#district').load('/location/district/', {'city':$('#city').val()}, function(){
			$('form#g_update_form select#district').each(function(){
				this.value=old_g_details.district;
			});
		});
	} 
	else{
		$('form#g_update_form select#district').each(function(){
			this.value=old_g_details.district;
		});
	}
	
}

function checkLength(o,n,min,max) {

	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("出错啦，" + n +"的长度"+ " 必须不小于"+min+" 并且不大于 "+max+"。");
		return false;
	} else {
		return true;
	}

}

function checkRegexp(o,regexp,n) {

	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('ui-state-error');
		updateTips(n);
		return false;
	} else {
		return true;
	}

}

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
//    var queryString = $.param(formData); 
	new_g_details={
		name:$('#g_update_name').val(),
		title:$('#g_update_title').val(),
		description:$('#g_update_desc').val(),
		member_limit:$('#g_update_limit').val(),
		photo:$('#g_update_photo').val(),
		city:$('#city').val(),
		district:$('#district').val()
	};
	if(reset_pressed)
	{
		reset_pressed = false;
		return false;
	}
	if(new_g_details.name == old_g_details.name
		&& new_g_details.title == old_g_details.title
		&& new_g_details.description == old_g_details.description
		&& new_g_details.member_limit == old_g_details.member_limit
		&& new_g_details.city == old_g_details.city
		&& new_g_details.district == old_g_details.district
		&& new_g_details.photo == old_g_details.photo)
	{
		return false;
	}
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  {
	//firstly check wether the city is changed.
	var reload_d = false;
	if(old_g_details.city != new_g_details.city){
		reload_d = true;
	}
	old_g_details = new_g_details;
	new_g_details='';
	
	$('#g_update_photo').val("");
	old_g_details.photo="";
	
	$('.g_name_field').each(function(){
		this.textContent = responseText.name;
	});
	$('.g_title_field').each(function(){
		this.textContent = responseText.title;
	});
	$('.g_description_field').each(function(){
		this.textContent = responseText.description;
	});
	$('.g_memeber_limit').each(function(){
		this.textContent = responseText.member_limit;
	});
	if(responseText.picture_url != undefined){
		$('a.g_pic_url').each(function(){
			var split_index = this.href.lastIndexOf('/group_pic/')
			var prefix = this.href.substring(0,split_index)
			this.href=prefix +'/group_pic/'+ responseText.picture_url;
		});
		$('img.g_pic_url').each(function(){
			var split_index = this.src.lastIndexOf('/group_pic/')
			var prefix = this.src.substring(0,split_index)
			this.src=prefix +'/group_pic/'+ responseText.picture_url;
		});
	}

	//location info
	$('#g_location').each(function(){
		this.textContent=responseText.city + responseText.district;
	});
	$('#city').each(function(){
		this.value=responseText.city;
	});
	
	$('#district').each(function(){
		this.value=responseText.district;
	});

} 